//优惠券
//相比优惠码，优惠券是一次性的，而且不可共享
(function() {
	var config = require("../_include/config");
	var db = require("../db/index");
	var md5 = require("../_include/md5");
	var helper = require("../_include/helper");
	var db_table_name = config.dbname.ticketFactory;
	var db_id_prefix = config.dbIdPrefix.ticketFactory;
	//构造函数
	var _con = function(info) {
		if (!info) {
			throwCusError("参数错误，优惠券信息不可为空");
		}
		var self = this;
		self._id = db_id_prefix + (+new Date).toString(36) + Math.random().toString(36).substr(2);
		self.bus_id = info.bus_id;

		self.info = {};
		self.setInfo(info);

		self.ticket_list = [];


		// self.buff_id; //真正有用的时候再动弹生成。

		self.create_time = +new Date;
		db.insert(db_table_name, self);
		console.log("生成了一个优惠券包：", self._id);
	};

	module.exports = _con;

	//技能
	_con.prototype = require("./skill");
	_con.TYPE = {
		打折: 1,
		满减: 2,
		现金抵用: 3
	};

	//静态方法
	_con.get = function(Id) {
		var result = db.find_by_id(db_table_name, Id);
		if (result) {
			result.__proto__ = _con.prototype;
		}
		return result;
	};
	//生成默认的描述信息
	_con.getIntro = function(instance) {
		var result = "";
		var config = instance.info.config;
		switch (instance.info.type) {
			case _con.TYPE.打折:
				if (config.is_grads) {

				} else {
					result += "折扣：{0} 折\n".format(config.discount);
				}
				break;
			case _con.TYPE.满减:
				if (config.is_grads) {

				} else {
					result += "满 {0} 减 {1}\n".format(config.full_cash, config.cut_cash);
				}
				break;
			case _con.TYPE.现金抵用:
				if (config.is_grads) {

				} else {
					result += "抵用金额：{0}\n".format(config.directly_cut_cash);
				}
				break;
		}
		//关于有效期
		if (instance.info.diedline == Number.MAX_VALUE) {
			result += "永久有效\n";
		} else {
			if (instance.info.diedline > +new Date) {
				result += "有效期至：{0}\n".format(new Date.format("yyyy年MM月dd号 HH:mm"));
			} else {
				result += "已过期\n";
			}
		}
		//关于使用次数
		result += "可用次数：{0}\n".format(instance.info.times)
		return result;
	}
	_con.canUseForAch = function(ticket_factory, ach) {
		var ticket_factory_info = ticket_factory.info;
		if (ticket_factory.bus_id !== ach.info.bus_id) {
			return false;
		}
		//如果没有限制，则默认通过，可无限制直接使用
		if (!(ticket_factory_info.goods_limit || ticket_factory_info.tag_limit)) {
			return true;
		}
		var res = false;
		if (ticket_factory_info.goods_limit) {
			var goods_limit_map = $Array.toMap(ticket_factory_info.goods_limit);
			res = ach.info.goods_info.some(function(goods_info) {
				//只要白名单名单中有一个包含是订单中的商品，这个就可以使用
				return goods_limit_map[goods_info.goods._id];
			});
		}
		if (!res && ticket_factory_info.tag_limit) {
			res = ach.info.goods_info.some(function(goods_info) {
				var tag_limit_map = $Array.toMap(ticket_factory_info.tag_limit);
				return goods_info.tags && goods_info.tags.some(function(tag_id) {
					return tag_limit_map[tag_id];
				});
			});
		}
		return res;
	};
	_con.ticketId_has_user = function(ticket_id, user_id) {
		return ticket_id.indexOf("|U:" + user_id) > -1;
	}

}());